package com.bruce.tool.web.filter.core;

import com.bruce.tool.common.util.file.FileUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class JsonRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public JsonRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        byte[] bytes = FileUtils.transfer(request.getInputStream());
        this.body = new String(bytes,StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
        return new DefaultInputStreamWraper(bais);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        return this.body;
    }
}
